//
//  LLPictureView.swift
//  xinlangweibo
//
//  Created by 任玉林 on 16/6/30.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit
// cell 可重用标识符
private let pictureViewCellId = "pictureViewCellId"
private let itemMargin: CGFloat = 5
private let cellWH : CGFloat = (SCREENW - OriginalMargin * 2 - itemMargin * 2) / 3

class LLPictureView: UICollectionView {
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //声明一个属性
    var pic_urls:[LLPictureInfoModel]?{
        
        didSet{
            
//            centerLable.text = "\(pic_urls?.count ?? 0)"
            
            let size = getPictureViewSize(pic_urls?.count ?? 0)
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.size.equalTo(size)
            }
            //刷新
            reloadData()
            
        }
    }
    
    //根据返回的图片数量计算size
    func getPictureViewSize(count:Int)->CGSize{
        
        //计算行.列
        let col = count == 4 ? 2 : (count >= 3 ? 3 :count)
        
        let row = count == 4 ? 2 : ((count - 1) / 3 + 1)
        
        //计算宽高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1) * itemMargin
        
        let h = CGFloat(row) * cellWH  + CGFloat(row - 1) * itemMargin
    
        return CGSize(width: w, height: h)
        
    }
    
    //设置视图
    func setupUI(){
        
        backgroundColor = UIColor.clearColor()
        
        //设置代理
        dataSource = self
        
        delegate = self
        
        //注册
       registerClass(LLPictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
        
        addSubview(centerLable)
        
        centerLable.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(self)
            
            //设置layout
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            
            layout.itemSize = CGSize(width: cellWH - 1, height: cellWH - 1)

            layout.minimumInteritemSpacing = itemMargin
            
            layout.minimumLineSpacing = itemMargin
            
        }
    }
    
    //懒加载
    private lazy var centerLable: UILabel = UILabel(textColor: UIColor.redColor(), textFont: 35)
    
}

//数据源方法
extension LLPictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        
        let cell = dequeueReusableCellWithReuseIdentifier(pictureViewCellId, forIndexPath: indexPath) as!LLPictureViewCell
        
        cell.picInfo = pic_urls![indexPath.item]
        

        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = pic_urls?.count ?? 0
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
    }
    
}

//自定义cell
class LLPictureViewCell: UICollectionViewCell {
    
    var picInfo:LLPictureInfoModel?{
        
        didSet{
            
            bgImageView.sd_setImageWithURL(NSURL(string: picInfo?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_card_top_background"))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置视图
    private func setupUI(){
        
        contentView.addSubview(bgImageView)
        
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
    }
    
    //懒加载
    private lazy var bgImageView: UIImageView = {
        
        let img = UIImageView(imageName: "timeline_card_top_background")
        
        //设置图片填充方式
        img.contentMode = .ScaleAspectFill
        
        img.clipsToBounds = true
        
        return img
        
    }()
    
}


extension LLPictureView: SDPhotoBrowserDelegate{
    
    // 返回临时占位图片（即原来的小图）
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
        let cell  =  self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as!LLPictureViewCell
        return cell.bgImageView.image
    }
    // 返回高质量图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlStr = (pic_urls![index].thumbnail_pic ?? "" as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: urlStr)
    }
}

